import React, { PureComponent } from 'react';
import { Card, Form, Row, Select, DatePicker, Button, Col, Spin } from 'antd';
import { Chart, Axis, Tooltip, Geom, Legend } from 'bizcharts';
import { connect } from 'dva';
import lodash from 'lodash';
import moment from 'moment';
import numeral from 'numeral';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
// import { SqlHistogramArray } from '../../utils/enum';
import { fmtDateTime } from '../../utils/fmt';
// import classNames from 'classnames';
import styles from './Jmvs.less'

@connect(({ GlobalEnumModel, JmvsModel, loading }) => ({
  GlobalEnumModel,
  JmvsModel,
  queryLoading: loading.effects['JmvsModel/findData'],
}))
@Form.create()
export default class Jmvs extends PureComponent {

  // 数据初始化
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'GlobalEnumModel/allSysName' });
    this.findDiffData();
  }

  // 查询数据
  findDiffData = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    dispatch({ type: 'JmvsModel/findData', payload: { ...queryParam, pageNo: 0 } });
  }

  // 查询表单
  queryForm() {
    const {
      form: { getFieldDecorator },
      queryLoading,
      GlobalEnumModel: { sysNameList, currentSysName },
      JmvsModel: { queryParam, longTimeList },
    } = this.props;
    return (
      <Form onSubmit={this.findDiffData} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="选择系统">
            {getFieldDecorator('index', { initialValue: currentSysName })(
              <Select placeholder="所属系统" allowClear={false} onChange={this.sysNameChange}>
                {sysNameList.map(({ index, sysName }) => (<Select.Option key={index} value={index}>{sysName}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="开始时间">
            {getFieldDecorator('startTime', { initialValue: queryParam.startTime })(
              <DatePicker
                style={{ width: undefined }}
                allowClear={false}
                format="YYYY-MM-DD HH:mm:ss"
                disabledDate={current => current > moment().add(0, 'day').endOf('day')}
                showTime={{ defaultValue: moment('08:00:00', 'HH:mm:ss') }}
                showToday={false}
              // renderExtraFooter={() => {
              //   return [
              //     <Tag key='1' color="blue">30天前</Tag>,
              //     <Tag key='2' color="blue">15天前</Tag>,
              //     <Tag key='3' color="blue">7天前</Tag>,
              //     <Tag key='7' color="blue">1天前</Tag>,
              //     <Tag key='4' color="blue">12小时前</Tag>,
              //     <Tag key='5' color="blue">6小时前</Tag>,
              //     <Tag key='6' color="blue">1小时前</Tag>,
              //   ];
              // }}
              />
            )}
          </Form.Item>
          <Form.Item label="持续时间">
            {getFieldDecorator('longTime', { initialValue: queryParam.longTime })(
              <Select placeholder="持续时间" allowClear={true}>
                {longTimeList.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={queryLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  getDiffHistogram() {
    const rowStyle = { paddingTop: 24, paddingBottom: 12, borderBottom: '1px solid #ccc' };
    const colStyle = { textAlign: 'center', color: 'blue' };
    const { JmvsModel: { data } } = this.props;
    const histogramArray = [];
    histogramArray.push((
      <div key='k1' style={rowStyle}>
        <Row key='k2' gutter={96}>
          <Col key='k5' span={1}>
            {/* {this.getPoint(data1 ? data1.totalData : undefined)} */}
          </Col>
          <Col key='k3' span={22}>
            {this.getMemoryArea(data)}
          </Col>
          <Col key='k4' span={1}>
            {/* {this.getPoint(data1 ? data1.totalData : undefined)} */}
          </Col>
        </Row>
        <div style={colStyle}>JVM内存使用</div>
      </div>
    ));
    histogramArray.push((
      <div key='k2' style={rowStyle}>
        <Row key='k2' gutter={96}>
          <Col key='k5' span={1}>
            {/* {this.getPoint(data1 ? data1.totalData : undefined)} */}
          </Col>
          <Col key='k3' span={22}>
            {this.getThreadArea(data)}
          </Col>
          <Col key='k4' span={1}>
            {/* {this.getPoint(data1 ? data1.totalData : undefined)} */}
          </Col>
        </Row>
        <div style={colStyle}>JVM线程使用</div>
      </div>
    ));
    return histogramArray;
  }

  bytesToMb = (bytes) => {
    return numeral(bytes / 1024 / 1024).format('0,000.00');
  }

  // 内存图
  getMemoryArea = (jvmData) => {
    if (!jvmData) return <span />;
    const data = [];
    lodash.each(jvmData, ({ _source }) => {
      if (!_source) return;
      const { memoryTotalUsed, memoryHeapUsed, memoryNonHeapUsed } = _source;
      data.push({ time: moment(_source['@timestamp']), value: this.bytesToMb(memoryTotalUsed), type: '内存总量' });
      // data.push({ time: moment(_source['@timestamp']), value: memoryTotalMax, type: '内存总量最大值' });
      data.push({ time: moment(_source['@timestamp']), value: this.bytesToMb(memoryHeapUsed), type: '堆内存' });
      // data.push({ time: moment(_source['@timestamp']), value: memoryHeapMax, type: '堆内存最大值' });
      data.push({ time: moment(_source['@timestamp']), value: this.bytesToMb(memoryNonHeapUsed), type: '非堆内存' });
    });
    const scale = {
      time: { type: 'time', alias: "时间", formatter: time => fmtDateTime(time) },
      value: { type: 'linear', min: 0, alias: "内存(MB)", formatter: bytes => `${bytes} MB` },
    };
    if (this.memoryArea) this.memoryArea.forceFit();
    return (
      <Chart
        forceFit={true}
        onGetG2Instance={memoryArea => { this.memoryArea = memoryArea }}
        // width={1000}
        height={350}
        padding={['auto', 120, 'auto', 'auto']}
        data={data}
        scale={scale}
      >
        <Axis name="time" title={{ position: "end" }} />
        <Axis name="value" title={{ offset: 70, position: "end" }} />
        <Legend layout="vertical" position="right" />
        <Tooltip crosshairs={{ type: "rect" }} showTitle={true} />
        <Geom type="area" position="time*value" color="type" shape="smooth" />
        <Geom type="line" position="time*value" color="type" shape="smooth" size={2} />
      </Chart>
    );
  }

  // 线程图
  getThreadArea = (jvmData) => {
    if (!jvmData) return <span />;
    const data = [];
    lodash.each(jvmData, ({ _source }) => {
      if (!_source) return;
      const { threadCount, threadDeadlocks, threadBlockedCount } = _source;
      data.push({ time: moment(_source['@timestamp']), value: threadCount, type: '线程总数量' });
      data.push({ time: moment(_source['@timestamp']), value: threadDeadlocks, type: '死锁线程数' });
      data.push({ time: moment(_source['@timestamp']), value: threadBlockedCount, type: '阻塞线程数' });
    });
    const scale = {
      time: { type: 'time', alias: "时间", formatter: time => fmtDateTime(time) },
      value: { type: 'linear', min: 0, alias: "线程数" },
    };
    if (this.threadArea) this.threadArea.forceFit();
    return (
      <Chart
        forceFit={true}
        onGetG2Instance={threadArea => { this.threadArea = threadArea }}
        // width={1000}
        height={350}
        padding={['auto', 120, 'auto', 'auto']}
        data={data}
        scale={scale}
      >
        <Axis name="time" title={{ position: "end" }} />
        <Axis name="value" title={{ position: "end" }} />
        <Legend layout="vertical" position="right" />
        <Tooltip crosshairs={{ type: "rect" }} showTitle={true} />
        <Geom type="area" position="time*value" color="type" shape="smooth" />
        <Geom type="line" position="time*value" color="type" shape="smooth" size={2} />
      </Chart>
    );
  }

  render() {
    const { queryLoading } = this.props;
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {/* {this.actionButton()} */}
          <Spin size="large" spinning={queryLoading || false}>
            {this.getDiffHistogram()}
          </Spin>
        </Card>
      </PageHeaderLayout>
    );
  }
}
